package com.example.pceb.utils;

/**
 * 自定义的日志记录工具类
 * 提供静态方法供其他类调用
 * 支持不同级别的日志记录（INFO、WARN、ERROR、DEBUG）
 * 自动获取当前线程名和时间戳
 * 处理异常堆栈信息
 */
import com.example.pceb.service.SystemLogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import jakarta.annotation.PostConstruct;

@Component
public class LogUtils {
    
    private static SystemLogService systemLogService;
    
    @Autowired
    private SystemLogService logService;
    
    @PostConstruct
    public void init() {
        LogUtils.systemLogService = this.logService;
    }
    
    /**
     * 记录INFO级别日志
     */
    public static void info(String logger, String message) {
        logToDatabase("INFO", logger, message, Thread.currentThread().getName(), null);
    }
    
    /**
     * 记录WARN级别日志
     */
    public static void warn(String logger, String message) {
        logToDatabase("WARN", logger, message, Thread.currentThread().getName(), null);
    }
    
    /**
     * 记录ERROR级别日志
     */
    public static void error(String logger, String message, Throwable throwable) {
        String stackTrace = null;
        if (throwable != null) {
            stackTrace = getStackTrace(throwable);
        }
        logToDatabase("ERROR", logger, message, Thread.currentThread().getName(), stackTrace);
    }
    
    /**
     * 记录ERROR级别日志（无异常）
     */
    public static void error(String logger, String message) {
        logToDatabase("ERROR", logger, message, Thread.currentThread().getName(), null);
    }
    
    /**
     * 记录DEBUG级别日志
     */
    public static void debug(String logger, String message) {
        logToDatabase("DEBUG", logger, message, Thread.currentThread().getName(), null);
    }
    
    private static void logToDatabase(String level, String logger, String message, String thread, String stackTrace) {
        if (systemLogService != null) {
            try {
                systemLogService.logToDatabase(level, logger, message, thread, stackTrace);
            } catch (Exception e) {
                System.err.println("记录日志到数据库失败: " + e.getMessage());
            }
        }
    }
    
    private static String getStackTrace(Throwable throwable) {
        StringBuilder sb = new StringBuilder();
        sb.append(throwable.toString()).append("\n");
        
        StackTraceElement[] elements = throwable.getStackTrace();
        for (StackTraceElement element : elements) {
            sb.append("\tat ").append(element.toString()).append("\n");
        }
        
        return sb.toString();
    }
} 